#include "StockPublisherService.hpp"
#include "Server.hpp"

namespace bagprod { namespace finance { namespace SPS {

void StockPublisherService::Initalize(int argc, char* argv[])
{   
    try
    {
        m_xmlExtractor->LoadXMLConfigurationFile("StockPublisherServiceConfig.xml");
        LoadXMLConfiguration();
        
        delete m_xmlExtractor;
        
        CreateDataCaches();
        
        // Register call backs.
        m_server->f_ptrGetStockDataByTicker = NULL;
        m_server->f_ptrGetCompanyName = NULL;
    }
    catch(std::exception &ex)
    {
        std::cerr << "Error loading configuration file.";
        delete m_xmlExtractor;
        exit(1);
    }
}
void StockPublisherService::CreateDataCaches()
{
    std::list<types::Stock*> stocks = m_databaseAccess->GetStocks();
    std::list<types::Stock*>::iterator it = stocks.begin();
    
    while(it != stocks.end())
    {
        // Ticker Stock Map
        m_TickerStockMap.insert( 
                std::pair<std::string,types::Stock*>(
                                        (*it)->get_ticker(),(*it)));
        
        // StockDataMap
        m_StockDataMap.insert(
            std::pair<std::string, std::list<types::StockData *>
            (
                (*it)->get_ticker(),
                m_databaseAccess->GetStockData( (*it)->get_stockId() )
            ));
    }
}
void StockPublisherService::Start()
{
    m_server->Run();
}
void StockPublisherService::Stop()
{

}
StockPublisherService::StockPublisherService()
{
    this->m_xmlExtractor = new XMLextractor();
    this->m_databaseAccess = new DBAccess();   
    this->m_server = new Server();
}
void StockPublisherService::LoadXMLConfiguration()
{
    this->m_databaseAccess->Initialize(
            m_xmlExtractor->GetNodeValue("database"),
            m_xmlExtractor->GetNodeValue("pricetable"),
            m_xmlExtractor->GetNodeValue("stocktable"),
            m_xmlExtractor->GetNodeValue("hostname"),
            m_xmlExtractor->GetNodeValue("username"),
            m_xmlExtractor->GetNodeValue("password"));
    
    this->m_server->Initialize(
            "127.0.0.1",
            5001);
}
StockPublisherService::~StockPublisherService()
{   
    std::map<std::string,std::list<types::StockData*> *>::iterator mapIt;
    std::list<types::StockData*>::iterator listIt;
    
    mapIt = StockPublisherService::m_stockDataCache.begin();
    
    while(!StockPublisherService::m_stockDataCache.empty())
    {
        std::list<types::StockData*> *dataList = mapIt->second;
        types::StockData* data;
        listIt = dataList->begin();
        
        while(!dataList->empty())
        {
            data = *listIt;
            delete data;
            listIt++;
        }
        
        delete dataList;
        mapIt++;
    }
}
}}} // namespace